﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Sharp.Infrastructure;
using Sharp.Infrastructure.IoC;
using Sharp.Portal.Configuration;
using Sharp.Portal.Interface;
using Sharp.Portal.Mvc.Form;
using Sharp.Portal.Other;

namespace Sharp.Portal.Mvc.List
{
    /// <summary>
    /// ListPage 实现
    /// </summary>
    public abstract partial class SharpList : ISharpList
    {
        private readonly ToolButtonOperateAction _oa = new ToolButtonOperateAction();


        public SharpList()
        {
            ColumnItems = new List<ColumnItem>();
            QueryItems = new List<QueryItem>();
            ToolButtons = new Dictionary<string, ToolButtonInfo>();
            ToolbarButtonParameters = new List<ToolButtonInfo>();

            StoreUrlAction = "GetPaged";
            ModuleId = this.GetType().FullName.Replace(".", "_");
            ItemPanelUrlAction = string.Empty;

            Load();
        }


        static SharpList()
        {

        }

        #region 工具栏按钮集合
        /// <summary>
        /// 工具栏按钮集合
        /// </summary>
        public Dictionary<string, ToolButtonInfo> ToolButtons { get; set; }

        #endregion

        /// <summary>
        /// 初始化工具栏按钮
        /// </summary>
        protected virtual void InitToolButtons()
        {
            foreach (var attr in
                GetType().GetCustomAttributes(typeof(DataHandlerAttribute), true)
                    .OfType<DataHandlerAttribute>()
                    .OrderBy(x => x.Order))
            {
                var handler = attr.GetHandler();

                var p = this.ToolbarButtonParameters.FirstOrDefault(x => x.Mode == attr.Mode);
                if (p != null)
                {
                    handler.Direct = p.Direct;
                    handler.Parameters = p.Parameters;
                }
                if (attr.Mode == ModuleOP.Edit)
                {
                    handler.WithoutId = false;
                }

                handler.HasWindow = new[] { OpenWith.Tile, OpenWith.Tile2Column }.All(o => o != this.GetModuleItemLayoutType());

                if (attr.Mode == ModuleOP.Delete)
                {
                    handler.HasWindow = false;
                }

                handler.Html = _oa.ExecuteOperate(attr.Mode, handler);

                ToolButtons.Add(attr.Mode, handler);
            }


        }

        /// <summary>
        /// 工具栏按钮适配器
        /// </summary>
        IToolButton ToolButtonProvider { get; set; }

        /// <summary>
        /// 特性
        /// </summary>
        public ListFeature Feature { get; set; }
        /// <summary>
        /// 按钮参数
        /// </summary>
        public IList<ToolButtonInfo> ToolbarButtonParameters { get; set; }

        /// <summary>
        /// 面包屑
        /// </summary>
        public string Breadcrumb { get; set; }
        /// <summary>
        /// 列
        /// </summary>
        public List<ColumnItem> ColumnItems { get; set; }
        /// <summary>
        /// 查询项
        /// </summary>
        public List<QueryItem> QueryItems { get; set; }

        public string ModuleId { get; set; }

        #region 获取列表标题

        /// <summary>
        /// 获取列表标题
        /// </summary>
        /// <returns></returns>
        protected virtual void InitTitle()
        {
            if (HideTitle)
            {
                PageTitle = "";
                return;
            }
            if (PageTitle.IsNullOrEmpty())
            {
                var title =
                    this.GetType().GetCustomAttributes(typeof(TitleAttribute), false)
                        .FirstOrDefault() as TitleAttribute;
                if (title != null)
                {
                    PageTitle = title.Title;
                }
                else
                {
                    PageTitle = "未定义标题";
                }
            }
        }

        #endregion

        /// <summary>
        /// 获取ItemPage模型
        /// </summary>
        /// <returns></returns>
        private Type GetModuleItem()
        {
            var moduleItem = this.GetType().GetCustomAttributes(typeof(ModuleItemAttribute), true).FirstOrDefault() as ModuleItemAttribute;

            return moduleItem?.Item;
        }

        private OpenWith ModuleItemLayoutType { get; set; }

        private OpenWith GetModuleItemLayoutType()
        {
            if (ModuleItemLayoutType != OpenWith.None)
            {
                return ModuleItemLayoutType;
            }
            var moduleItem = GetModuleItem();
            if (moduleItem == null)
            {
                return OpenWith.None;
                //throw new NotImplementedException("List页需要配置ModuleItem以便于获取Item页的LayoutType配置");
            }
            var itemPageAttribute = moduleItem.GetCustomAttributes(typeof(ItemPageAttribute), false).FirstOrDefault() as ItemPageAttribute;
            if (itemPageAttribute == null)
            {
                return OpenWith.Window2Column;
            }
            ModuleItemLayoutType = itemPageAttribute.OpenWith;
            return ModuleItemLayoutType;
        }

        /// <summary>
        /// 数据控件的Id
        /// </summary>
        public string ListControlId { get; set; }
        /// <summary>
        /// Store的Action名称
        /// </summary>
        /// <example>可以接受GetPaged或者GetPaged,User。它会自己转换为Url.Action相关形式</example>
        public string StoreUrlAction { get; set; }

        /// <summary>
        /// 页面标题
        /// </summary>
        public string PageTitle { get; set; }

        /// <summary>
        /// 隐藏标题
        /// </summary>
        public bool HideTitle { get; set; }
        /// <summary>
        /// 布局
        /// </summary>
        public LayoutInfo Layout { get; set; }


        /// <summary>
        /// 加载模型时必须执行，无论模板是否已经生成
        /// </summary>
        private void Load()
        {
            InitTitle();
        }

        /// <summary>
        /// 初始化完成
        /// </summary>
        public virtual void InitComplete()
        {
            ToolButtonProvider = ServiceLocator.Instance.GetService<IToolButton>();
            if (ToolButtonProvider == null)
            {
                throw new NotImplementedException("请实现IToolButton接口或者配置好接口与实现类。");
            }

            ToolButtonProvider.ListPage = this;

            _oa.GatherOperate("Details", ToolButtonProvider.DetailsButton);
            _oa.GatherOperate("Create", ToolButtonProvider.CreateButton);
            _oa.GatherOperate("Edit", ToolButtonProvider.EditButton);
            _oa.GatherOperate("Delete", ToolButtonProvider.DeleteButton);
            _oa.GatherOperate("Refresh", ToolButtonProvider.RefreshButton);
            _oa.GatherOperate("Custom", ToolButtonProvider.CustomButton);


            InitToolButtons();
            InitDataList();
            InitQueryPanel();
            if (ItemPanelWidth.IsEmpty())
            {
                ItemPanelWidth = 320;
            }
            HandleMobileDevice();

            if (GetEnableOrgTreeLayout() && IsUseOrgTreeLayout)
            {
                Layout = new LayoutInfo()
                {
                    LayoutPath = "~/Areas/Platform/Views/Shared/_OrgTreeLayout.cshtml",
                    SectionName = "tabContent"
                };
            }
        }
        /// <summary>
        /// 是否使用组织界面布局
        /// </summary>
        public bool IsUseOrgTreeLayout { get; set; }

        /// <summary>
        /// 是否可编辑
        /// </summary>
        /// <returns></returns>
        public bool Editable()
        {
            //如果嵌套到表单里面会收到是否只读的参数
            bool.TryParse(HttpContext.Current.Request.Params["IsReadOnlyForm"], out var hiddenToolButton);
            //if (hiddenToolButton)
            //    this.Feature = this.Feature | ListFeature.HiddenToolButton;
            return hiddenToolButton;
        }

        public virtual void HandleMobileDevice()
        {
        }

        /// <summary>
        /// 偏好的实现类
        /// </summary>
        public Type Preference { get; set; }
        /// <summary>
        /// 系统配置实现类
        /// </summary>
        public Type SystemConfig { get; set; }
        /// <summary>
        /// 获取页码定义
        /// </summary>
        /// <returns></returns>
        public int GetPageSizeDefine()
        {
            if (this.Preference == null) return 15;

            var config = UserConfigManage.Read(Preference) as IPreferenceConfig;

            return config.PageSize;
        }

        public bool GetEnableOrgTreeLayout()
        {
            if (this.SystemConfig == null) return false;

            var config = SystemConfigManage.Read(SystemConfig) as ISystemConfig;

            return config.EnableOrgTreeLayout;
        }


        /// <summary>
        /// 适配器
        /// </summary>
        public ITemplateProvider Provider { get; set; }

        public ITemplateProvider GetProvider()
        {
            InitProvider();
            return Provider;
        }

        /// <summary>
        /// 初始化适配器
        /// </summary>
        public virtual void InitProvider()
        {

        }

        /// <summary>
        /// 是否为移动设备
        /// </summary>
        /// <returns></returns>
        public static bool IsMobileDevice()
        {
            string[] mobileAgents = { "iphone", "android", "phone", "mobile", "wap", "netfront", "java", "opera mobi", "opera mini", "ucweb", "windows ce", "symbian", "series", "webos", "sony", "blackberry", "dopod", "nokia", "samsung", "palmsource", "xda", "pieplus", "meizu", "midp", "cldc", "motorola", "foma", "docomo", "up.browser", "up.link", "blazer", "helio", "hosin", "huawei", "novarra", "coolpad", "webos", "techfaith", "palmsource", "alcatel", "amoi", "ktouch", "nexian", "ericsson", "philips", "sagem", "wellcom", "bunjalloo", "maui", "smartphone", "iemobile", "spice", "bird", "zte-", "longcos", "pantech", "gionee", "portalmmm", "jig browser", "hiptop", "benq", "haier", "^lct", "320x320", "240x320", "176x220", "w3c ", "acs-", "alav", "alca", "amoi", "audi", "avan", "benq", "bird", "blac", "blaz", "brew", "cell", "cldc", "cmd-", "dang", "doco", "eric", "hipt", "inno", "ipaq", "java", "jigs", "kddi", "keji", "leno", "lg-c", "lg-d", "lg-g", "lge-", "maui", "maxo", "midp", "mits", "mmef", "mobi", "mot-", "moto", "mwbp", "nec-", "newt", "noki", "oper", "palm", "pana", "pant", "phil", "play", "port", "prox", "qwap", "sage", "sams", "sany", "sch-", "sec-", "send", "seri", "sgh-", "shar", "sie-", "siem", "smal", "smar", "sony", "sph-", "symb", "t-mo", "teli", "tim-", "tosh", "tsm-", "upg1", "upsi", "vk-v", "voda", "wap-", "wapa", "wapi", "wapp", "wapr", "webc", "winw", "winw", "xda", "xda-", "googlebot-mobile" };

            bool isMoblie = false;

            if (HttpContext.Current.Request.UserAgent != null)
            {
                string userAgent = HttpContext.Current.Request.UserAgent.ToLower();

                //排除 Windows 桌面系统或苹果桌面系统 
                if (!string.IsNullOrEmpty(userAgent) && !userAgent.Contains("macintosh") && (!userAgent.Contains("windows nt") || (userAgent.Contains("windows nt") && userAgent.Contains("compatible; msie 9.0;"))))
                {
                    for (int i = 0; i < mobileAgents.Length; i++)
                    {
                        if (userAgent.IndexOf(mobileAgents[i], StringComparison.Ordinal) >= 0)
                        {
                            isMoblie = true;
                            break;
                        }
                    }
                }
            }

            return isMoblie;
        }
    }
}